package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.MessageDao;
import com.rk.kbk.dao.MessageUnitDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Message;
import com.rk.kbk.model.MessageUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.math.BigInteger;
import java.util.List;

/**
 * @MessageController
 * @消息Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/message")
public class MessageController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageUnitDao messageUnitDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改消息
     * @param message
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateMessage",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateMessage(@RequestBody Message message){
        log.debug("添加/修改消息");
        messageDao.save(message);
        return JsonResp.ok();
    }

    /**
     * @按钮添加消息
     * @param title
     * @param content
     * @param messUrlUrl
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addMessage",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addMessage( String title,String content,String messUrlUrl ){
        log.debug("添加消息");
        Message m=new Message();
        m.setTitle(title);
        m.setContent(content);
        m.setMessUrl(messUrlUrl);
        messageDao.save(m);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改消息
     * @param messages
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeMessage",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeMessage(@RequestBody List<Message> messages){
        log.debug("批量添加/修改消息");
        messageDao.save(messages);
        return JsonResp.ok();
    }

    /**
     * @获取消息详情-ByMessageId
     * @param messageId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/messageDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findMessageDetailsByMessageId(Long messageId) {
        log.debug("获取消息详情-ByMessageId");
        return JsonResp.ok(messageDao.findOne(messageId));
    }

    /**
     * @分页查询消息(jpa方式)
     * @param message 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageMessageJpa(@RequestBody(required = false) Message message, Integer pageNum, Integer pageSize) {
        log.debug("分页查询消息(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == message) {
            page = messageDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  message.getUserName();
            page = messageDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<Message> content = page.getContent();
//        for (Message message1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除消息-one(永久)
     * @param messageId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteMessageOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteMessageOne(Long messageId) {
        log.debug("删除消息-one(永久)");
        Message message=messageDao.findOne(messageId);
        List<MessageUnit> ms=messageUnitDao.findByMessage(message);
        messageUnitDao.delete(ms);
        messageDao.delete(messageId);
        return JsonResp.ok();
    }

    /**
     * @批量删除消息(永久)
     * @param messages
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeMessage",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeMessage(@RequestBody List<Message> messages) {
        log.debug("批量删除消息(永久)");
        messageDao.delete(messages);
        return JsonResp.ok();
    }

    /**
     * @分页查询消息(jpa方式)
     * @param userType 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/pageshow",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageMessageJpa2(  Integer pageNum, Integer pageSize,Integer userType) {
        log.debug("分页查询消息(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (userType==0) {
            page = messageDao.findAll(pageable); //无条件分页
        }else{

            page = messageDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        expressions.add(cb.equal(root.get("userType"), userType));
                        return predicate;
                    }, pageable);
        }
//        List<Message> content = page.getContent();
//        for (Message message1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }


}
